package com.idol.gateway;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.*;

/**
 * @author SupremeSir
 * @description Spring Cloud 网关
 * @className GlobeGatewayFailter
 * @date 2021/2/16 0:28
 **/
@Component
public class GlobeGatewayFailter implements GlobalFilter, Ordered {
    private static final Map<String, LinkedList<Long>> BLACK_LIST = new HashMap<>();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        // 放行验证码相关和用户登录接口
        if (path.startsWith("/code") || path.startsWith("/user/login")) {
            return chain.filter(exchange);
        }
        // 处理用户注册接口
        if (path.startsWith("/user/register")) {
            // 获取请求主机IP
            String host = request.getHeaders().getFirst("Host").split(":")[0];
            if (StringUtils.isEmpty(host)) {
                response.setStatusCode(HttpStatus.BAD_REQUEST);
                DataBuffer buffer = response.bufferFactory().wrap("无法获取主机IP".getBytes());
                return response.writeWith(Mono.just(buffer));
            }
            // 根据访问IP，获取该机器注册次数信息
            LinkedList<Long> registTimeList = BLACK_LIST.get(host);
            long currentTime = System.currentTimeMillis();
            if (registTimeList != null) {
                boolean timeFlag = currentTime - registTimeList.getFirst() > 60000;
                boolean countFlag = registTimeList.size() <= 100;

                // 1分钟内注册超过100次，禁止注册
                if (!timeFlag && !countFlag) {
                    response.setStatusCode(HttpStatus.BAD_REQUEST);
                    DataBuffer buffer = response.bufferFactory().wrap("行为异常，请稍后重试".getBytes());
                    return response.writeWith(Mono.just(buffer));
                } else {
                    // 遍历获取一分钟以外的记录索引
                    List<Integer> indexList = new ArrayList<>();
                    for (int i = 0; i < registTimeList.size(); i++) {
                        Long time = registTimeList.get(i);
                        if ((currentTime - time) > 60000) {
                            indexList.add(i);
                        } else {
                            break;
                        }
                    }
                    // 清除一分钟以外的记录
                    for (int i : indexList) {
                        registTimeList.remove(i);
                    }
                    // 添加当次记录
                    registTimeList.add(currentTime);
                }
            } else {
                LinkedList<Long> list = new LinkedList<>();
                list.add(currentTime);
                BLACK_LIST.put(host, list);
            }
            // 网关过滤器放行
            return chain.filter(exchange);
        }

        // 检测请求的 Cookie并获取 Token
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        String token = null;
        for (Map.Entry<String, List<HttpCookie>> entry : cookies.entrySet()) {
            List<HttpCookie> value = entry.getValue();
            for (HttpCookie cookie : value) {
                if ("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                }
            }
        }
        // 获取 Token 失败重定向至登录页面
        if (null == token) {
            response.setStatusCode(HttpStatus.FOUND);
            response.getHeaders().setLocation(URI.create("http://192.168.32.102/static/login.html"));
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
